package com.music.pay.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.music.pay.dto.AlipayDto;
import com.music.pay.feign.OrderFeign;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("/pay/web")
public class AlipayController {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private AlipayTradePagePayRequest alipayRequest;

    @Resource
    private OrderFeign orderFeign;

    @RequestMapping(value = "/alipay")
    @ResponseBody
    public String alipay(AlipayDto alipayDto) {
        alipayRequest.setReturnUrl(alipayRequest.getReturnUrl() + alipayDto.getOut_trade_no());

        try {
            alipayRequest.setBizContent(new ObjectMapper().writeValueAsString(alipayDto));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        // 请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            // 输出 返回
            System.out.println(result);
            System.out.println("returnUrl = " + alipayRequest.getReturnUrl());
            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

}
